<template>
  <div class="page-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Download /></el-icon>
          <span>导出管理</span>
        </div>
      </template>

      <div class="export-section">
        <el-alert
          title="导出说明"
          type="info"
          description="您可以导出排考结果的Excel文件，包含完整的监考安排和优化结果统计信息。"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        />

        <div v-if="!hasAssignments" class="no-data">
          <el-empty description="暂无排考结果，请先进行排考">
            <el-button type="primary" @click="$router.push('/schedule')">
              前往排考
            </el-button>
          </el-empty>
        </div>

        <div v-else class="export-content">
          <!-- 统计信息展示 -->
          <div class="stats-preview">
            <h3>排考统计信息</h3>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card class="stat-card">
                  <el-statistic title="总考试数量" :value="examCount" prefix="共" suffix="场" />
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <el-statistic title="参与教师数量" :value="teacherCount" prefix="共" suffix="人" />
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <el-statistic title="总监考人次" :value="totalAssignments" prefix="共" suffix="人次" />
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="6">
                <el-card class="stat-card">
                  <el-statistic title="总出行次数" :value="stats?.totalTrips || 0" />
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <el-statistic title="最大监考次数" :value="stats?.maxAssignments || 0" />
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <el-statistic title="最小监考次数" :value="stats?.minAssignments || 0" />
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <el-statistic title="目标函数值" :value="stats?.objectiveValue || 0" />
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 导出操作 -->
          <div class="export-actions">
            <h3>导出操作</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card class="action-card">
                  <template #header>
                    <div class="action-header">
                      <el-icon><DocumentAdd /></el-icon>
                      <span>导出排考结果</span>
                    </div>
                  </template>
                  <p>导出完整的排考结果Excel文件，包含考试信息、监考教师安排等详细数据。</p>
                  <el-button 
                    type="primary" 
                    @click="exportExcel"
                    :loading="exporting"
                    style="width: 100%;"
                  >
                    <el-icon><Download /></el-icon>
                    导出Excel文件
                  </el-button>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="action-card">
                  <template #header>
                    <div class="action-header">
                      <el-icon><DataAnalysis /></el-icon>
                      <span>查看详细统计</span>
                    </div>
                  </template>
                  <p>查看排考算法的详细统计信息和优化结果分析。</p>
                  <el-button 
                    type="success" 
                    @click="showStatsDialog = true"
                    style="width: 100%;"
                  >
                    <el-icon><View /></el-icon>
                    查看统计详情
                  </el-button>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 排考结果预览 -->
          <div class="preview-section">
            <h3>排考结果预览</h3>
            <el-table 
              :data="assignments.slice(0, 10)" 
              style="width: 100%"
              stripe
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            >
              <el-table-column prop="exam_name" label="考试名称" min-width="150" />
              <el-table-column prop="exam_id" label="考试编号" width="120" />
              <el-table-column prop="exam_time" label="考试时间" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.exam_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="teacher_name" label="监考教师" width="120" />
              <el-table-column prop="employee_id" label="工号" width="100" />              <el-table-column prop="lives_in_weishui" label="渭水居住" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.lives_in_weishui ? 'success' : 'info'">
                    {{ scope.row.lives_in_weishui ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="assignments.length > 10" class="more-data">
              <p>还有 {{ assignments.length - 10 }} 条记录，请导出Excel查看完整数据</p>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 统计详情对话框 -->
    <el-dialog title="排考统计详情" v-model="showStatsDialog" width="600px">
      <div v-if="stats" class="stats-detail">
        <el-descriptions title="优化目标统计" :column="2" border>
          <el-descriptions-item label="总出行次数">{{ stats.totalTrips }}</el-descriptions-item>
          <el-descriptions-item label="目标函数值">{{ stats.objectiveValue }}</el-descriptions-item>
          <el-descriptions-item label="最大监考次数">{{ stats.maxAssignments }}</el-descriptions-item>
          <el-descriptions-item label="最小监考次数">{{ stats.minAssignments }}</el-descriptions-item>
          <el-descriptions-item label="监考次数差值">
            <el-tag :type="stats.assignmentDifference <= 2 ? 'success' : 'warning'">
              {{ stats.assignmentDifference }}
              ({{ stats.assignmentDifference <= 2 ? '符合要求' : '超出要求' }})
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="公平性评估">
            <el-tag :type="stats.assignmentDifference <= 2 ? 'success' : 'warning'">
              {{ stats.assignmentDifference <= 2 ? '良好' : '需要优化' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="optimization-info" style="margin-top: 20px;">
          <h4>优化算法说明</h4>
          <ul>
            <li>目标函数 = 总出行次数 + 监考次数差值 × 10</li>
            <li>优先安排工号较大的教师，确保监考次数相对均衡</li>
            <li>考虑教师上课时间和不可用时间冲突</li>
            <li>最大化减少教师往返学校的次数</li>
          </ul>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, DocumentAdd, DataAnalysis, View } from '@element-plus/icons-vue'
import { exportApi } from '@/api/export'

interface Assignment {
  exam_name: string
  exam_id: string
  exam_time: string
  teacher_name: string
  employee_id: string
  lives_in_weishui: boolean
}

interface Stats {
  totalTrips: number
  maxAssignments: number
  minAssignments: number
  assignmentDifference: number
  objectiveValue: number
}

const assignments = ref<Assignment[]>([])
const stats = ref<Stats | null>(null)
const exporting = ref(false)
const showStatsDialog = ref(false)

const hasAssignments = computed(() => assignments.value.length > 0)

const examCount = computed(() => {
  const uniqueExams = new Set(assignments.value.map(a => a.exam_id))
  return uniqueExams.size
})

const teacherCount = computed(() => {
  const uniqueTeachers = new Set(assignments.value.map(a => a.employee_id))
  return uniqueTeachers.size
})

const totalAssignments = computed(() => assignments.value.length)

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const loadAssignments = async () => {
  try {
    const data = await exportApi.getAssignments()
    assignments.value = data
  } catch (error) {
    console.log('暂无排考数据')
  }
}

const exportExcel = async () => {
  if (!hasAssignments.value) {
    ElMessage.warning('暂无排考结果可导出')
    return
  }

  exporting.value = true
  try {
    await exportApi.exportExcel()
    ElMessage.success('Excel文件导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

onMounted(() => {
  loadAssignments()
  // 从localStorage获取统计数据（如果有的话）
  const savedStats = localStorage.getItem('scheduleStats')
  if (savedStats) {
    stats.value = JSON.parse(savedStats)
  }
})
</script>

<style scoped>
.page-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-icon {
  color: #409EFF;
  font-size: 18px;
}

.export-section {
  padding: 20px;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
}

.export-content h3 {
  color: #409EFF;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

.stats-preview {
  margin-bottom: 40px;
}

.stat-card {
  text-align: center;
  background: rgba(64, 158, 255, 0.05);
  border: 1px solid rgba(64, 158, 255, 0.2);
}

.export-actions {
  margin-bottom: 40px;
}

.action-card {
  height: 180px;
  transition: all 0.3s ease;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.action-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.preview-section {
  margin-bottom: 20px;
}

.more-data {
  text-align: center;
  padding: 15px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 8px;
  margin-top: 10px;
  color: #409EFF;
}

.stats-detail h4 {
  color: #409EFF;
  margin-bottom: 10px;
}

.optimization-info ul {
  margin: 10px 0;
  padding-left: 20px;
}

.optimization-info li {
  margin-bottom: 8px;
  color: #606266;
}

:deep(.el-table) {
  background-color: transparent;
}

:deep(.el-table tr) {
  background-color: transparent;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: rgba(0, 0, 0, 0.02);
}

:deep(.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-statistic__content) {
  font-size: 20px;
  font-weight: 600;
}
</style>
